//
//  vbo_only.cpp
//  Sierpinski
//
//  Created by wneqi on 14-5-19.
//  Copyright (c) 2014年 wneqi. All rights reserved.
//

#include <stdio.h>
#include <GLUT/glut.h>
#include "vbo_only.h"

static float vertices[3][2] =
{
    {0, 0},
    {0, 1},
    {1, 0}
};
static float color[3][3] =
{
    {1, 0, 0},
    {0, 1, 0},
    {0, 0, 0}
};

static float another_vertices [3][2] =
{
    {0, 0},
    {0, -1},
    {-1, 0}
};
static float another_color[3][3] =
{
    {1, 0, 0},
    {0, 1, 0},
    {0, 0, 0}
};

static GLuint vbo[2];

void init_vbo_only_main (int argc, char** argv)
{
    glutInit (&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize (800, 600);
    glutInitWindowPosition (100, 100);
    glutCreateWindow ("Hello, VBO Only");
    glutDisplayFunc (display_vbo_only);
    init_vbo_only_gl ();
    glutMainLoop ();
}

void init_vbo_only_gl ()
{
    // 构建vbo
    glGenBuffers (2, vbo);
    
    // 设置第一个三角形的VBO
    glBindBuffer (GL_ARRAY_BUFFER, vbo[0]);
    // 将数据提交到GPU中，预申请顶点坐标+顶点颜色内存块
    glBufferData (GL_ARRAY_BUFFER, sizeof (vertices) + sizeof (color), NULL, GL_STATIC_DRAW);
    // 提交顶点坐标
    glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (vertices), vertices);
    // 提交顶点颜色
    glBufferSubData (GL_ARRAY_BUFFER, sizeof (vertices), sizeof (color), color);
    
    // 设置第二个三角形的VBO
    glBindBuffer (GL_ARRAY_BUFFER, vbo[1]);
    glBufferData (GL_ARRAY_BUFFER, sizeof (another_vertices) + sizeof (another_color), NULL, GL_STATIC_DRAW);
    glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (another_vertices), another_vertices);
    glBufferSubData (GL_ARRAY_BUFFER, sizeof (another_vertices), sizeof (another_color), another_color);
    
    glClearColor (1, 1, 1, 1);
    
    glEnableClientState (GL_VERTEX_ARRAY);
    glEnableClientState (GL_COLOR_ARRAY);

}

void display_vbo_only ()
{
    glClear (GL_COLOR_BUFFER_BIT);
    
    // 绘制第一个三角形
    glBindBuffer (GL_ARRAY_BUFFER, vbo[0]);
    // 设置要绘制的顶点坐标数组，对应的数据存储在当前激活的VBO中
    glVertexPointer (2, GL_FLOAT, 0, 0);
    // 设置要绘制的顶点颜色数组，对应的数据存储在当前激活的VBO中
    glColorPointer (3, GL_FLOAT, 0, (GLvoid*)(sizeof (vertices)));
    // 绘制数据
    glDrawArrays (GL_TRIANGLES, 0, 3);
    
    // 绘制第二个三角形
    glBindBuffer (GL_ARRAY_BUFFER, vbo[1]);
    glVertexPointer (2, GL_FLOAT, 0, 0);
    glColorPointer (3, GL_FLOAT, 0, (GLvoid*)sizeof (another_vertices));
    glDrawArrays (GL_TRIANGLES, 0, 3);
    
    glFlush ();

}





